package com.gmq.mianshi.designModel.observe.subject;

import com.gmq.mianshi.designModel.observe.observer.Observer;

import java.util.Enumeration;
import java.util.Vector;

/**
 * 具体主题ConcreteSubject
 *
 * @author gmq
 * @email 2628931@qq.com
 * @date 2017/11/27 14:34
 */
public class ConcreteSubject implements Subject {

    // 用一向量vector来维持观察者队列
    private Vector observersVector = new Vector();

    @Override
    public void registerObserver(Observer observer) {
        observersVector.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observersVector.remove(observer);
    }

    @Override
    public void notifyObserver() {
        System.out.println("主题有所改变，通知观察者");
        // 复制一份观察者列表，这样可以避免线程安全问题
        Enumeration enumeration = ((Vector) observersVector.clone()).elements();
        // 逐个通知观察者
        while (enumeration.hasMoreElements()) {
            ((Observer)enumeration.nextElement()).update();
        }
    }
}
